package com.jhh.pay.center.actor;

import com.jhh.pay.center.api.data.CfgRequest;
import com.jhh.pay.center.model.PayChannel;
import com.jhh.pay.center.service.PayChannelCfgService;
import com.jhh.pay.center.service.PayChannelService;
import com.jhh.pay.center.service.cloud.PayChannelTemplate;
import com.jhh.pay.center.service.cloud.message.QueryResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author tangxd
 * @Description: TODO
 * @date 2017/12/19
 */
@Service("CfgActor")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Slf4j
public class CfgActor extends TradeActor {

    @Autowired
    private PayChannelService channelService;

    @Autowired
    private PayChannelTemplate template;

    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .match(CfgRequest.class, r -> {

                    PayChannel channel = channelService.getByKey(r.getChannelKey());
                    if (channel == null) {
                        sender().tell(new QueryResult<Map<String, Object>>(false, "通道不存在", null), self());
                        context().stop(self());
                        return;
                    }

                    try {
                        Map<String, Object> result = template.cfg(channel, r.getVersion());
                        sender().tell(new QueryResult<>(true, "ok", result), self());
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error(e.getMessage(), e);
                        sender().tell(new QueryResult<Map<String, Object>>(false, "连接通道失败", null), self());
                    } finally {
                        context().stop(self());
                    }
                })
                .build();
    }
}
